package com.atguigu.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.support.Parameter;
import com.atguigu.entity.HouseImage;
import com.atguigu.result.Result;
import com.atguigu.service.HouseImageService;
import com.atguigu.util.QiniuUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.UUID;

@Controller
@RequestMapping("houseImage")
public class HouseImageController {

    @Reference
    private HouseImageService houseImageService;

    @GetMapping("uploadShow/{houseId}/{type}")
    public String uploadShow(@PathVariable Long houseId, @PathVariable Integer type, Model model){
        model.addAttribute("houseId",houseId);
        model.addAttribute("type",type);
        System.out.println("================================================");
        System.out.println(type);
        return "house/upload";
    }

    @RequestMapping("upload/{houseId}/{type}")
    @ResponseBody
    public Result upload(@PathVariable Long houseId, @PathVariable Integer type, @RequestParam("file") MultipartFile [] files) throws IOException {
        if(files.length>0){
            for (MultipartFile file:files){
                String fileName = UUID.randomUUID().toString();
                String name = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
                fileName += name;
                QiniuUtil.upload2Qiniu(file.getBytes(),fileName);
                HouseImage houseImage = new HouseImage();
                houseImage.setHouseId(houseId);
                houseImage.setImageName(fileName);
                houseImage.setImageUrl("http://rik6lgdtu.hb-bkt.clouddn.com/"+fileName);
                houseImage.setType(type);
                houseImageService.insert(houseImage);
            }
        }

        return Result.ok();
    }

    @GetMapping("delete/{houseId}/{id}")
    public String delete(@PathVariable Long houseId,@PathVariable Long id){
        houseImageService.delete(id);
        return "redirect:/house/"+houseId;
    }

}
